import React from 'react';
import { View, Text, Image, StyleSheet, ActivityIndicator, TouchableOpacity } from 'react-native';
import theme from '../../styles/theme';

export interface ChatMessageProps {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  images?: string[];
  timestamp: Date;
  isLoading?: boolean;
  isError?: boolean;
  onRetry?: () => void;
  onImagePress?: (url: string) => void;
}

export const ChatMessage: React.FC<ChatMessageProps> = ({
  role,
  content,
  images = [],
  timestamp,
  isLoading = false,
  isError = false,
  onRetry,
  onImagePress,
}) => {
  const isUser = role === 'user';

  const formatTime = (date: Date): string => {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  };

  return (
    <View style={[
      styles.container,
      isUser ? styles.userContainer : styles.assistantContainer
    ]}>
      <View style={styles.messageHeader}>
        <Text style={styles.role}>{isUser ? '我' : '通义千问'}</Text>
        <Text style={styles.timestamp}>{formatTime(timestamp)}</Text>
      </View>

      <View style={styles.contentContainer}>
        {content ? (
          <Text style={styles.content}>{content}</Text>
        ) : null}

        {images && images.length > 0 && (
          <View style={styles.imageContainer}>
            {images.map((url, index) => (
              <TouchableOpacity
                key={`${url}-${index}`}
                onPress={() => onImagePress && onImagePress(url)}
                style={styles.imageWrapper}
              >
                <Image
                  source={{ uri: url }}
                  style={styles.image}
                  resizeMode="cover"
                />
              </TouchableOpacity>
            ))}
          </View>
        )}

        {isLoading && (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="small" color={theme.colors.primary.main} />
            <Text style={styles.loadingText}>正在思考...</Text>
          </View>
        )}

        {isError && (
          <View style={styles.errorContainer}>
            <Text style={styles.errorText}>消息发送失败</Text>
            {onRetry && (
              <TouchableOpacity onPress={onRetry} style={styles.retryButton}>
                <Text style={styles.retryText}>重试</Text>
              </TouchableOpacity>
            )}
          </View>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: theme.spacing.md,
    marginVertical: theme.spacing.xs,
    maxWidth: '85%',
    borderRadius: theme.borderRadius.lg,
  },
  userContainer: {
    alignSelf: 'flex-end',
    backgroundColor: theme.colors.primary.light,
    borderColor: theme.colors.primary.main,
    borderWidth: 1,
  },
  assistantContainer: {
    alignSelf: 'flex-start',
    backgroundColor: theme.colors.background.paper,
    borderColor: theme.colors.divider,
    borderWidth: 1,
  },
  messageHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: theme.spacing.xs,
  },
  role: {
    fontSize: theme.typography.fontSize.sm,
    fontWeight: theme.typography.fontWeight.medium,
    color: theme.colors.text.secondary,
  },
  timestamp: {
    fontSize: theme.typography.fontSize.xs,
    color: theme.colors.text.hint,
    marginLeft: theme.spacing.sm,
  },
  contentContainer: {
    gap: theme.spacing.sm,
  },
  content: {
    fontSize: theme.typography.fontSize.md,
    lineHeight: theme.typography.lineHeight.md,
    color: theme.colors.text.primary,
  },
  imageContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: theme.spacing.xs,
    marginTop: theme.spacing.xs,
  },
  imageWrapper: {
    borderRadius: theme.borderRadius.md,
    overflow: 'hidden',
    borderWidth: 1,
    borderColor: theme.colors.divider,
  },
  image: {
    width: 150,
    height: 150,
    backgroundColor: theme.colors.gray[300],
  },
  loadingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: theme.spacing.sm,
  },
  loadingText: {
    marginLeft: theme.spacing.sm,
    fontSize: theme.typography.fontSize.sm,
    color: theme.colors.text.secondary,
  },
  errorContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: theme.spacing.sm,
  },
  errorText: {
    fontSize: theme.typography.fontSize.sm,
    color: theme.colors.error.main,
  },
  retryButton: {
    marginLeft: theme.spacing.sm,
    padding: theme.spacing.xs,
    backgroundColor: theme.colors.error.light,
    borderRadius: theme.borderRadius.sm,
  },
  retryText: {
    fontSize: theme.typography.fontSize.sm,
    color: theme.colors.error.main,
    fontWeight: theme.typography.fontWeight.medium,
  }
});